import { useState } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Form, Input, Button, Toast } from '@nutui/nutui-react-taro';
import { loginApi } from '@/api/handleLogin';
import { searchUserInfoApi } from '@/api/handleUserAccount';
import { useUserStore } from '@/store/user';
import './login.scss';

function Login(){
  const store = useUserStore();
  const initForm = {
    userName: '111',
    password: '123123',
  }
  const [formInstance] = Form.useForm()
  const showNutToast = (msg, type = 'text') => {
    Toast.show({
      content: msg,
      duration: 1,
    })
  };

  const goToFindPassword = () => {
    Taro.navigateTo({ url: '/pages/find-password/find-password' });
  };

  const goToRegister = () => {
    Taro.navigateTo({ url: '/pages/register-account/register-account' });
  };

  const handleLogin = async () => {
    let formState = formInstance.getFieldsValue(true)
    try {
      const res = await loginApi(formState);
      console.log('loginn-res',res)
      if (res) {
        Taro.setStorageSync('localDb', 'false')
        Taro.setStorageSync('token', res.token)
        const result = await searchUserInfoApi();
        store.updateUserInfo(result);
        const userRes = store.getUserInfo();

        if (userRes?.roles?.length > 0) {
          Taro.redirectTo({ url: '/pages/home/home' });
        } else {
          Taro.redirectTo({ url: '/pages/welcome/welcome' });
        }
      }
    } catch (error) {
      console.error('Login failed:', error);
      showNutToast('登录失败', 'fail');
    }
  };

  return (
    <View className='loginPage'>
      <Text className='title'>一日之计</Text>
      <View className='loginForm'>
        <Form 
          form={formInstance}
          initialValues={initForm}
          onFinish={handleLogin}
        >
          <Form.Item
            label='用户名'
            align="center"
            required
            name="userName"
            rules={[
              { required: true, message: '请输入字段A' },
            ]}
          >
            <Input placeholder='请输入用户名'/>
          </Form.Item>
            
          <Form.Item
            label='密码'
            align="center"
            required
            name="password"
            rules={[
              { required: true, message: '请输入字段A' },
            ]}
          >
            <Input
              type='password'
              placeholder='请输入密码'
            />
          </Form.Item>
        </Form>
        <View className='help'>
          <Text onClick={goToFindPassword}>忘记密码</Text>
          <Text onClick={goToRegister}>注册账号</Text>
        </View>
        <Button nativeType="submit" onClick={()=>formInstance.submit()} className='loginBtn' type='primary' >
          登录
        </Button>
      </View>
    </View>
  );
};

export default Login;